/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.sys.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;

import com.moon.admin.framework.cache.CacheService;
import com.moon.admin.framework.util.SecurityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.moon.admin.framework.config.SystemConfig;
import com.moon.admin.framework.domain.MoonPage;
import com.moon.admin.framework.secure.AuthUtils;
import com.moon.admin.framework.secure.annotation.FormRepeat;
import com.moon.admin.framework.secure.annotation.PreAuth;
import com.moon.admin.framework.secure.domain.AuthInfo;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.framework.springmvc.domain.RCode;
import com.moon.admin.framework.syslog.annotation.SysLog;
import com.moon.admin.framework.util.JsonUtils;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.sys.cache.UserCache;
import com.moon.admin.sys.SysConstants;
import com.moon.admin.sys.domain.query.UserQuery;
import com.moon.admin.sys.entity.SysUserEntity;
import com.moon.admin.sys.service.SysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 用户Controller
 * 
 * @author ninglong
 */
@RestController
@RequestMapping(value = "sysUser")
@Api(value="用户管理",tags="用户管理")
@Slf4j
public class SysUserController {
	
	@Autowired
	private SysUserService userService;
	@Autowired
	private CacheService cacheService;
	@Autowired
	private SystemConfig systemConfig;

	@PostMapping(value = "list")
	@ApiOperation(value="用户列表")
	public R<MoonPage<SysUserEntity>> list(@RequestBody UserQuery query) {
		IPage<SysUserEntity> page = userService.selectListPage(query);
		return R.success(MoonPage.of(page));
	}
	
	@PostMapping(value = "save")
	@ApiOperation(value="保存用户信息")
	@PreAuth("sys_user_edit")
	@SysLog(mod="用户管理",fun="保存用户")
	@FormRepeat
	public R<String> save(@RequestBody SysUserEntity userEntity){
		if(ToolUtils.isEmpty(userEntity.getPhoneNumber())){
			return R.fail(RCode.PARAM_ERROR.getCode(),"手机号码不能为空");
		}
		//判断当前账号是否存在
		if(ToolUtils.isEmpty(userEntity.getId())){
			QueryWrapper<SysUserEntity> ew = new QueryWrapper<SysUserEntity>();
			ew.eq("phoneNumber", userEntity.getPhoneNumber());
			int count = userService.count(ew);
			if(count>0){
				return R.fail(RCode.PARAM_ERROR.getCode(),"手机号码【"+userEntity.getPhoneNumber()+"】已存在");
			}
		}
		if(userEntity.getPostIdDeptIds().contains(userEntity.getMainPostIdDeptId())){
			return R.fail(RCode.PARAM_ERROR.getCode(),"副岗位中包含了主岗位，请重新选择");
		}
		userEntity.setPassword(SecurityUtils.md5(SysConstants.DEFAULT_PASSWORD));
		userService.saveUser(userEntity);
		UserCache.cleanCache();
		return R.success();
	}
	
	@PostMapping(value = "saveInfo")
	@ApiOperation(value="修改个人信息")
	@PreAuth("sys_user_edit")
	@SysLog(mod="用户管理",fun="修改个人信息")
	@FormRepeat
	public R<String> saveInfo(@RequestBody SysUserEntity userEntity){
		if(ToolUtils.isEmpty(userEntity.getPhoneNumber())){
			return R.fail(RCode.PARAM_ERROR.getCode(),"手机号码不能为空");
		}
		//判断当前账号是否存在
		if(ToolUtils.isEmpty(userEntity.getId())){
			QueryWrapper<SysUserEntity> ew = new QueryWrapper<SysUserEntity>();
			ew.eq("phoneNumber", userEntity.getPhoneNumber());
			int count = userService.count(ew);
			if(count>0){
				return R.fail(RCode.PARAM_ERROR.getCode(),"手机号码【"+userEntity.getPhoneNumber()+"】已存在");
			}
		}
		userService.updateById(userEntity);
		UserCache.cleanCache();
		return R.success();
	}
	
	@GetMapping(value = "updateUserStatusById")
	@ApiOperation(value="根据id修改用户状态")
	@PreAuth("sys_user_edit")
	@SysLog(mod="用户管理",fun="根据id修改用户状态")
	public R<Void> updateUserStatusById(Integer userId,Integer status) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setId(userId);
		userEntity.setStatus(status);
		userService.updateById(userEntity);
		return R.success();
	}
	
	@GetMapping(value = "restPassword")
	@ApiOperation(value="重置密码")
	@SysLog(mod="用户管理",fun="重置密码")
	@PreAuth("sys_user_restpwd")
	public R<Void> restPassword(Integer accountId){
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setId(accountId);
		if(accountId==1){
			return R.fail(RCode.PARAM_ERROR.getCode(),"超级管理员的密码不能重置");
		}
		userEntity.setPassword(SecurityUtils.md5(SysConstants.DEFAULT_PASSWORD));
		userService.updateById(userEntity);
		return R.success();
	}
	
	@GetMapping(value = "modifyPassword")
	@ApiOperation(value="修改密码")
	@SysLog(mod="用户管理",fun="修改密码")
	public R<Void> modifyPassword(String password,String newPassword){
		SysUserEntity account = new SysUserEntity();
		account.setId(AuthUtils.getCurrentUserId());
		if(account.getId()==1){
			return R.fail(RCode.PARAM_ERROR.getCode(),"超级管理员的密码不能修改");
		}
		SysUserEntity tmpUser = UserCache.getUserById(account.getId());
		if(!tmpUser.getPassword().equals(SecurityUtils.md5(password))){
			return R.fail(RCode.PARAM_ERROR.getCode(),"原密码不正确，请输入正确的密码");
		}
		account.setPassword(SecurityUtils.md5(newPassword));
		userService.updateById(account);
		cacheService.del(UserCache.USER_BY_ID_CACHE+tmpUser.getId());
		return R.success();
	}
	
	@PostMapping(value = "modifyAvatar")
	@ApiOperation(value="修改用户头像")
	@SysLog(mod="用户管理",fun="修改用户头像",isSaveRequestData=false)
	public R<String> modifyAccountAvatar(@RequestParam("avatarfile") MultipartFile file){
		LocalDate date = LocalDate.now();
		String fileName = ToolUtils.getLowerUUID()+".png";
		String remoteFileDirStr = "/avatar/" + date.getYear() + "/" + date.getMonthValue() + "/" + date.getDayOfMonth() + "/";
		File remoteFileDir = new File(systemConfig.getTmpDir()+remoteFileDirStr);
		if(!remoteFileDir.exists()) {
			remoteFileDir.mkdirs();
		}
		try {
			IOUtils.copy(file.getInputStream(), new FileOutputStream(new File(remoteFileDir.getAbsolutePath()+"/"+fileName)));
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		String avatar = remoteFileDirStr+fileName;
		AuthInfo authInfo = AuthUtils.getAuthInfo(AuthUtils.getCurrentUserId());
		SysUserEntity account = new SysUserEntity();
		account.setId(authInfo.getId());
		account.setAvatar(avatar);
		userService.updateById(account);
		//更新缓存中头像路径
		authInfo.setAvatar(avatar);
		AuthUtils.setAuthInfo(authInfo);
		return R.success(avatar);
	}

	@GetMapping("/cleanCache")
	@ApiIgnore
	public R<Void> cleanCache(){
		UserCache.cleanCache();
		return R.success();
	}
}